package com.linewow.xhyy.nihaonew.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.linewow.xhyy.hrxb.Constant;
import com.linewow.xhyy.hrxb.activity.ChatActivity;
import com.linewow.xhyy.nihaonew.R;
import com.linewow.xhyy.nihaonew.activity.TopicDetailActivity;
import com.linewow.xhyy.nihaonew.activity.UserMineActivity;
import com.linewow.xhyy.nihaonew.adapter.FindTagTopicAdapter;
import com.linewow.xhyy.nihaonew.application.NiHaoApp;
import com.linewow.xhyy.nihaonew.base.BaseFragment;
import com.linewow.xhyy.nihaonew.base.BaseInfo;
import com.linewow.xhyy.nihaonew.entity.image.SimpleImagesInfo;
import com.linewow.xhyy.nihaonew.entity.tag.CustomTagsInfo;
import com.linewow.xhyy.nihaonew.entity.topic.FindTagTopicInfo;
import com.linewow.xhyy.nihaonew.entity.user.Uinfo;
import com.linewow.xhyy.nihaonew.model.HttpModel;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;

/**
 * Created by LXR on 2016/9/8.
 * 标签内容界面
 */
public class TagDetailFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener, BaseQuickAdapter.RequestLoadMoreListener {
    @Bind(R.id.tag_detail_recycler)
    RecyclerView tagDetailRecycler;
    @Bind(R.id.tag_detail_refresh)
    SwipeRefreshLayout tagDetailRefresh;
    private String key = "msg";
    private String TAG = "TagDetailFragment";
    private String tagId;
    private Type tagDetailType;
    private Gson gson;
    private List<FindTagTopicInfo<Uinfo, SimpleImagesInfo, CustomTagsInfo>> findTagTopicInfos;
    private FindTagTopicAdapter adapter;
    private int page=1;
    @Override
    public View initView() {
        View view = View.inflate(getActivity(), R.layout.fragment_tag_detail, null);
        ButterKnife.bind(this, view);
        LinearLayoutManager manager = new LinearLayoutManager(TagDetailFragment.this.getActivity());
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        tagDetailRefresh.setColorSchemeColors(Color.RED,Color.BLACK);
        tagDetailRefresh.setOnRefreshListener(TagDetailFragment.this);
        tagDetailRecycler.setLayoutManager(manager);
        tagDetailRecycler.setItemAnimator(new DefaultItemAnimator());
        return view;
    }

    @Override
    public void initList() {
        super.initList();

        tagDetailRecycler.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void SimpleOnItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                Log.e(TagDetailFragment.this.TAG,"点击了"+i+"---"+findTagTopicInfos.get(i).avatar);
                startDetailActivity(findTagTopicInfos.get(i).tid);
            }
        });

        tagDetailRecycler.addOnItemTouchListener(new OnItemChildClickListener() {
            @Override
            public void SimpleOnItemChildClick(BaseQuickAdapter baseQuickAdapter, View view, final int i) {
                int id=view.getId();
                final FindTagTopicInfo<Uinfo, SimpleImagesInfo, CustomTagsInfo>info=findTagTopicInfos.get(i);
                switch (id){
                    case R.id.widget_topic_menu_like_rela:

//                        if(info.zan.equals("0")){
//                            NiHaoOkgo.zanInfo(info)
//                                    .subscribeOn(Schedulers.io())
//                                    .observeOn(AndroidSchedulers.mainThread())
//                                    .subscribe(new Action1<NiHaoGeneral<String>>() {
//                                        @Override
//                                        public void call(NiHaoGeneral<String> stringNiHaoGeneral) {
//                                            if(stringNiHaoGeneral.status){
//                                                info.setZan("1");
//                                                int upnum=Integer.parseInt(info.upnum);
//                                                info.setUpnum(Integer.toString(++upnum));
//                                                adapter.notifyItemChanged(i);
//                                            }
//                                        }
//                                    });
//                        }else{
//                            NiHaoOkgo.zanInverseInfo(info)
//                                    .subscribeOn(Schedulers.io())
//                                    .observeOn(AndroidSchedulers.mainThread())
//                                    .subscribe(new Action1<NiHaoGeneral<String>>() {
//                                        @Override
//                                        public void call(NiHaoGeneral<String> stringNiHaoGeneral) {
//                                            if(stringNiHaoGeneral.status){
//                                                info.setZan("0");
//                                                int upnum=Integer.parseInt(info.upnum);
//                                                info.setUpnum(Integer.toString(--upnum));
//                                                adapter.notifyItemChanged(i);
//                                            }
//                                        }
//                                    });
//
//                        }

                        break;
                    case R.id.widget_topic_menu_conversation_rela:

                        if(noLogin()){
                            return;
                        }

                        if(info.uid!=null&&!info.uid.equals(NiHaoApp.uid)){
                            Intent intent=new Intent(getActivity(), ChatActivity.class);
                            intent.putExtra(Constant.EXTRA_CHAT_TYPE, Constant.CHATTYPE_SINGLE );
                            intent.putExtra(Constant.EXTRA_USER_ID, info.uid);
                            startActivity(intent);
                        }



                        break;

                    case R.id.widget_personal_message_avatar:

                        if(noLogin()){
                            return;
                        }
                        startUserActivity(info.uinfo);
                        break;
                }
            }
        });




    }

    @Override
    public void initData() {
        super.initData();
        initGson();
        tagId = getArguments().getString(key);
        findTagTopicInfos=new ArrayList<FindTagTopicInfo<Uinfo, SimpleImagesInfo, CustomTagsInfo>>();
        requestInfo();
    }

    private void initGson() {
        gson = new Gson();
        tagDetailType = new TypeToken<BaseInfo<FindTagTopicInfo<Uinfo, SimpleImagesInfo, CustomTagsInfo>>>() {
        }.getType();
    }




    private void requestInfo() {
        pullUp();
    }

    private void pullUp() {
        page=1;
        refreshData(page);
    }

    private void refreshData(int page) {
        OkHttpUtils.get().url(HttpModel.TOPICTAGDETAIL + tagId+"&token="+ NiHaoApp.token+"&page="+page)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }
                    @Override
                    public void onResponse(String response, int id) {
                        tagDetailRefresh.setRefreshing(false);
                        BaseInfo<FindTagTopicInfo<Uinfo, SimpleImagesInfo, CustomTagsInfo>> baseInfo = gson.fromJson(response, tagDetailType);
                        if(adapter==null){
//                            findTagTopicInfos.addAll(baseInfo.data);
                            adapter = new FindTagTopicAdapter( findTagTopicInfos);
                            adapter.isFirstOnly(false);
                            adapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
                            adapter.setOnLoadMoreListener(TagDetailFragment.this);
                            adapter.addData(baseInfo.data);
                            tagDetailRecycler.setAdapter(adapter);
                        }else{
                            adapter.setNewData(baseInfo.data);
                            Log.e(TAG,"刷新数据大小111"+findTagTopicInfos.size());
                        }
                    }
                });
    }


    @Override
    public void onRefresh() {
        pullUp();
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onLoadMoreRequested() {
        upDown();
    }

    private void upDown() {
        page++;
        loadData(page);
    }

    private void loadData(int page) {
        Log.e(TAG, "上拉加载" + page);
        OkHttpUtils.get().url(HttpModel.TOPICTAGDETAIL + tagId+"&token="+ NiHaoApp.token+"&page="+page)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        adapter.showLoadMoreFailedView();
                    }
                    @Override
                    public void onResponse(String response, int id) {
                        tagDetailRefresh.setRefreshing(false);
                        BaseInfo<FindTagTopicInfo<Uinfo, SimpleImagesInfo, CustomTagsInfo>> baseInfo = gson.fromJson(response, tagDetailType);
                        if(adapter!=null){
                            adapter.addData(baseInfo.data);
                            if(findTagTopicInfos.size()<5){
                                adapter.loadComplete();
                            }
                            Log.e(TAG,"加载的数据的大小111"+findTagTopicInfos.size());
                        }
                    }
                });
    }


    public void startDetailActivity(String tid){
        Intent intent=new Intent(TagDetailFragment.this.getActivity(), TopicDetailActivity.class);
        intent.putExtra("msg",tid);
        startActivity(intent);
    }

    private void startUserActivity(Uinfo info) {
        Intent intent=new Intent(TagDetailFragment.this.getActivity(), UserMineActivity.class);
        Bundle bundle=new Bundle();
        bundle.putParcelable("info",info);
        intent.putExtras(bundle);
        startActivity(intent);
    }
}
